<template>
  <el-form label-width="80px" :model="skuInfo" :rules="rules" ref="skuForm">
    <el-form-item label="Spu名称">
      <span>{{ skuInfo.skuName }}</span>
    </el-form-item>
    <el-form-item label="Sku名称" prop="skuName">
      <el-input placeholder="请输入Sku名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input-number v-model="skuInfo.price" controls-position="right" @change="handleChange" :min="1" :max="10" style="width: 100%"></el-input-number>
    </el-form-item>
    <el-form-item label="重量" prop="weight">
      <el-input-number v-model="skuInfo.weight" controls-position="right" @change="handleChange" :min="1" :max="10" style="width: 100%"></el-input-number>
    </el-form-item>
    <el-form-item label="Sku描述" prop="skuDesc">
      <el-input placeholder="请输入Sku描述信息" type="textarea" v-model="skuInfo.skuDesc"></el-input>
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row>
        <el-col :sm="12" :md="8" :lg="6" v-for="(attr, index) in attrList" :key="attr.id">
          <el-form-item :label="attr.attrName">
            <el-select placeholder="请选择" v-model="skuInfo.skuAttrValueList[index]">
              <el-option :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" v-for="attrValue in attr.attrValueList" :key="attrValue.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueListValidate">
      <el-col :sm="12" :md="8" :lg="6" v-for="spuSaleAttr in spuSaleAttrList" :key="spuSaleAttr.id">
        <el-form-item :label="spuSaleAttr.saleAttrName">
          <el-select placeholder="活动区域">
            <el-option :label="saleAttr.saleAttrValueName" :value="saleAttr.id" v-for="saleAttr in spuSaleAttr.spuSaleAttrValueList" :key="saleAttr.id"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table border style="margin-bottom: 20px" :data="spuImageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="75" align="center"></el-table-column>
        <el-table-column label="图片" align="center">
          <template v-slot="{ row }">
            <el-image style="width: 100%; height: 100%" :src="row.imgUrl"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="imgName"></el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button v-if="row.isDefault === '0'" type="primary" @click="setDefault(row)">设置成默认图片</el-button>
            <el-button v-else type="success" disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="$emit('update:visible', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { reqGetAttrList } from '@/api/product/attr'
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { mapState } from 'vuex'
export default {
  name: 'SaveSku',
  data() {
    const skuImageListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择至少一张图片')
        return
      }
      callback()
    }
    const skuAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个平台属性')
        return
      }
      callback()
    }
    const skuSaleAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个销售属性')
        return
      }
      callback()
    }
    return {
      attrList: [],
      spuImageList: [],
      spuSaleAttrList: [],
      skuInfo: {
        skuName: '', // SKU名称
        skuDefaultImg: '', // 默认图片
        skuDesc: '', // sku描述
        price: 0, // 价格
        weight: '', // 重量
        skuAttrValueList: [], // 平台属性
        skuImageList: [], // 所选图片的集合
        skuSaleAttrValueList: [] // 销售属性
      },
      rules: {
        skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
        skuDesc: [{ required: true, message: '请输入SKU描述', trigger: 'blur' }],
        skuImageList: [
          {
            required: true,
            validator: skuImageListValidate,
            trigger: 'change'
          }
        ],
        skuAttrValueList: [
          {
            required: true,
            validator: skuAttrValueListValidate,
            trigger: 'change'
          }
        ],
        skuSaleAttrValueList: [
          {
            required: true,
            validator: skuSaleAttrValueListValidate,
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    ...mapState('spu', ['spuId']),
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  async mounted() {
    const { category1Id, category2Id, category3Id, spuId } = this
    const [responseAttrList, responseSpuImageList, responseSpuSaleAttrList] = await Promise.allSettled([reqGetAttrList({ category1Id, category2Id, category3Id }), reqGetSpuImageList(spuId), reqGetSpuSaleAttrList(spuId)])
    // console.log(responseSpuSaleAttrList)
    if (responseAttrList.status === 'fulfilled') {
      this.attrList = responseAttrList.value.data
    }
    if (responseSpuImageList.status === 'fulfilled') {
      this.spuImageList = responseSpuImageList.value.data.map((item) => {
        return {
          ...item, // 对象中原来的属性，依然显示在这里
          isDefault: '0' // 再添加一个属性
        }
      })
    }
    if (responseSpuSaleAttrList.status === 'fulfilled') {
      this.spuSaleAttrList = responseSpuSaleAttrList.value.data
    }
  },
  methods: {
    handleChange() {},
    //设置默认图片
    setDefault(row) {
      // 先把所有的设置为0
      this.spuImageList.forEach((item) => {
        item.isDefault = '0'
      })
      //在把当前的设置为1
      row.isDefault = '1'
      //保存一下默认图片的地址
      this.skuInfo.skuDefaultImg = row.imgUrl
    },
    //收集所选的图片数据
    handleSelectionChange(value) {
      this.skuInfo.skuImageList = value
    },
    //校验
    submitForm() {
      this.$refs.skuForm.validate(async (valid) => {
        if (valid) {
          if (!this.skuInfo.skuImageList) {
            this.$message.error('请设置默认照片！')
            return
          }
          const { spuId, category3Id } = this
          const { skuName, price, skuDesc, weight, skuDefaultImg, skuImageList, skuAttrValueList, skuSaleAttrValueList } = this.skuInfo
          const result = await reqSaveSkuInfo({
            spuId,
            category3Id,
            skuName,
            price,
            skuDesc,
            weight,
            skuDefaultImg,
            skuImageList,
            skuAttrValueList: skuAttrValueList.filter(Boolean).map((item) => {
              const { arrtId, attrName, valueId, valueName } = item.split(':')
              return {
                arrtId,
                attrName,
                valueId,
                valueName
              }
            }),
            skuSaleAttrValueList: skuSaleAttrValueList.filter(Boolean).map((item) => {
              const { saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName } = item.split(':')
              return {
                saleAttrId,
                saleAttrName,
                saleAttrValueId,
                saleAttrValueName
              }
            })
          })
          if (result.code === 200) {
            this.$message.success('添加sku成功!')
            this.$emit('update:visible', 1)
          } else {
            this.$message.error('添加sku失败!')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style>
</style>